'use strict';

const fs = require("fs");
const path = require('path')
const inquirer = require('inquirer')
const Command = require('@alic-cli-dev/command')
const log = require('@alic-cli-dev/log')


class RenameCommand extends Command {
    init() {
        this.updateName = this._argv[0] || ''
        this.newName = this._argv[1] || ''
        this.force = !!this.cmd.force
        log.verbose('updateName', this.updateName)
        log.verbose('newName', this.newName)
        log.verbose('force', this.force)
    }
    async exec() {
        let ifContinue = false
        if(!this.force) {
            ifContinue = (await inquirer.prompt({
                type: 'confirm',
                name: 'ifContinue',
                default: true,
                message: `是否将<${this.updateName}>替换为<${this.newName}>`
            })).ifContinue
            if(!ifContinue) return
        }
        if(this.force || ifContinue) {
            const url = process.cwd()
            await this.readDir(url)
            log.success('执行成功！')
        }
    }
    async readDir(url) {
        const files = fs.readdirSync(url)
        // 修改前的内容
        const updateStr = this.updateName
        // 要替换的内容
        let newStr = this.newName
        files.forEach((file, index) => {
          if (file.includes(updateStr)) {
            let newName = file.replace(updateStr, newStr)
            fs.rename(`${url + '/' + files[index]}`, `${url + '/' + newName}`, (err, file) => {
              if (err) {
                log.error(newName + " 已重命名！")
              }
              if (file) {
                log.success(newName + " 已重命名！")
              }
            })
          }
          const location = path.join(url, file)
      
          const info = fs.statSync(location)
          if(info.isDirectory()){
            this.readDir(location)
          }
        });
        
      }
}

function rename(argv) {
    return new RenameCommand(argv)
}

module.exports = rename
module.exports.RenameCommand = RenameCommand